

use std::{fs::{remove_dir_all, remove_file}, path::PathBuf};

use clap::Args;
use serde::{Deserialize, Serialize};
use wtask_base::{error::WResult, export::log_info, timer::{TimerAppTrait, TimerList, TimerRun}};

use crate::{task::utils::{func::archv_task_result, timer::TimerApp}, utils::AppTrait};





#[derive(Debug, Clone, Serialize, Deserialize, Args)]
pub struct AppTaskTimerAdd {
    /// 定时运行，定时设置提供一个字符串，分钟级定时。
    /// 其中以空格分为几个时间设置字段，各个时间设置如果不提供默认为_1，即每单位时间运行。
    /// 每个字段表示该字段运行的约束时间，如果前缀为_则表示间隔时间。
    /// 所有顺序字段：min/hour/day/week/month/year;
    /// 例1：每分钟运行："";
    /// 例2：每天上午10点0分运行："0 10";
    /// 例3：每月1日上午10点的每分钟运行："_1 10 1";
    /// 例4：每3个月的1日上午10点的每15分钟运行："_15 10 1 _1 _3"
    pub(crate) timer: String,
    
    #[command(subcommand)]
    pub(crate) app: TimerApp,
}


impl AppTrait for AppTaskTimerAdd {
    type Status = ();
    type Res = String;

    async fn server_handle_single(self) -> WResult<String> {
        let t = TimerRun::<TimerApp>::new(&self.timer, self.app)?;
        let r = format!("Timer Add: {}", t.name);
        t.save().await?;
        Ok(r)
    }
}



#[derive(Debug, Clone, Serialize, Deserialize, Args)]
pub struct AppTaskTimerStatus {
    /// 根据名字删除Timer
    #[arg(long)]
    pub(crate) del: Option<String>,

    /// 将任务运行记录删除
    #[arg(long)]
    pub(crate) result_del: bool,

    /// 将任务运行记录存档
    #[arg(long)]
    pub(crate) result_archv: bool,
}

impl AppTrait for AppTaskTimerStatus {
    type Status = ();
    type Res = TimerList<PathBuf>;

    async fn server_handle_single(self) -> WResult<TimerList<PathBuf>> {
        let timer_all_path_temp = TimerApp::get_all_timer().await?;
        let timer_del = if let Some(timer_del) = self.del {
            timer_del
        } else {
            "".to_string()
        };

        let mut data = Vec::new();
        for p in timer_all_path_temp {
            let meta_temp = TimerRun::<TimerApp>::load(&p).await?;
            if meta_temp.name != timer_del {
                data.push(meta_temp.to_fmt());
                continue;
            }
            log_info!("Del Timer: {p:?}");
            remove_file(p)?;
            if self.result_del || self.result_archv {
                for dir_task in meta_temp.logs() {
                    if self.result_del {
                        log_info!("Del Timer Result: {:?}", dir_task);
                        remove_dir_all(dir_task)?;
                    } else {
                        log_info!("Archv Timer Result: {:?}", dir_task);
                        archv_task_result(dir_task)?;
                    }
                }
            }
        };
        
        Ok(TimerList { data })
    }
}


